package com.sqpoll.android.poll;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.MenuItem;
import com.sqpoll.android.R;
import com.sqpoll.android.widget.ExpandableHeightListView;

/**
 * The activity for poll detail.
 * 
 * @author Younggue Bae
 */
public class PollDetailActivity extends SherlockFragmentActivity {

	public static final String TAG = "PollDetailActivity";
	public static final int MODIFY_MODE = 1;
	public static final int READ_MODE = 2;
	
	private String mPollId;
	private String mPollType;
	
	private int mViewMode = MODIFY_MODE;
	private ExpandableHeightListView mListViewAnswerChoice;
	private ExpandableHeightListView mListViewComment;
	private AnswerChoiceListAdapter mAdapterAnswerChoice;
	private CommentListAdapter mAdapterComment;
	private TextView mCreateUsername;
	private TextView mCreateDate;
	private TextView mCommentCount;
	private TextView mVoterCount;
	private TextView mQuestion;
	private ImageView mQuestionImage;
	private TableRow mQuestionMediaArea;
	private LinearLayout mLayoutFormControls;
	private LinearLayout mLayoutCommentForm;
	private Button mButtonSubmitPoll;
	private Button mButtonViewCommentForm;
	private Button mButtonSubmitComment;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_poll_detail);
		
		Intent intent = getIntent();
		mPollId = intent.getStringExtra("id");
		mPollType = intent.getStringExtra("type");
		String question = intent.getStringExtra("question");
		
		ActionBar actionBar = getSupportActionBar();
		actionBar.setDisplayShowTitleEnabled(true);
		actionBar.setHomeButtonEnabled(true);
		actionBar.setDisplayHomeAsUpEnabled(true);
		
		mCreateUsername = (TextView) findViewById(R.id.username);
		mCreateDate = (TextView) findViewById(R.id.create_date);
		mCommentCount = (TextView) findViewById(R.id.comment_count);
		mVoterCount = (TextView) findViewById(R.id.voter_count);
		mQuestion = (TextView) findViewById(R.id.question);
		mQuestionImage = (ImageView) findViewById(R.id.image_question);
		mQuestionMediaArea = (TableRow) findViewById(R.id.question_media_area);
		
		mLayoutFormControls = (LinearLayout) findViewById(R.id.layout_form_controls);
		mLayoutCommentForm = (LinearLayout) findViewById(R.id.layout_comment_form);
		mButtonSubmitPoll = (Button) findViewById(R.id.button_submit_poll);
		mButtonSubmitPoll.setOnClickListener(mSubmitPollButtonClickListener);
		mButtonViewCommentForm = (Button) findViewById(R.id.button_view_comment_form);
		mButtonViewCommentForm.setOnClickListener(mViewCommentFormButtonClickListener);
		mButtonSubmitComment = (Button) findViewById(R.id.button_submit_comment);
		mButtonSubmitComment.setOnClickListener(mSubmitCommentButtonClickListener);
		
		if (mViewMode == READ_MODE) {
			mLayoutFormControls.setVisibility(View.INVISIBLE);
			mLayoutCommentForm.setVisibility(View.VISIBLE);
		}
		else {
			mLayoutFormControls.setVisibility(View.VISIBLE);
			mLayoutCommentForm.setVisibility(View.INVISIBLE);
		}
		
		// TODO get the poll from server
		Poll poll = new Poll();
		//poll.setQuestionType(Poll.MULTIPLE_CHOICE_TYPE);
		poll.setQuestionType(Poll.SINGLE_CHOICE_TYPE);
		poll.setUsername("Sonya Cho");
		poll.setCreateDate("07.10");
		poll.setCommentCount(777);
		poll.setVoterCount(1707);
		
		Drawable drawable = poll.getPollImage();
		if (drawable != null) {
			mQuestionMediaArea.setVisibility(View.VISIBLE);
			setImageBitmap(drawable, mQuestionImage);
		}
		
		mQuestion.setText(question);
		mCreateUsername.setText(poll.getUsername());
		mCreateDate.setText(poll.getCreateDate());
		mCommentCount.setText(String.valueOf(poll.getCommentCount()));
		mVoterCount.setText(String.valueOf(poll.getVoterCount()));
		
		// answer choice list
		mListViewAnswerChoice = (ExpandableHeightListView) findViewById(R.id.list_view_answer_choice);
		mListViewAnswerChoice.setExpanded(true, false);

		mAdapterAnswerChoice = new AnswerChoiceListAdapter(this, poll, mViewMode);

		List<AnswerChoice> answerChoices = loadAnswerChoices(mPollId);
		mAdapterAnswerChoice.addItems(answerChoices);
		mAdapterAnswerChoice.notifyDataSetChanged();
		
		mListViewAnswerChoice.setOnItemClickListener(mAnswerChoiceItemClickListener);
		
		mListViewAnswerChoice.setAdapter(mAdapterAnswerChoice);
		
		// comment list
		mListViewComment = (ExpandableHeightListView) findViewById(R.id.list_view_comment);
		mListViewComment.setExpanded(true, true);
		
		mAdapterComment = new CommentListAdapter(this);
		
		List<Comment> comments = loadComments(mPollId);
		mAdapterComment.addItems(comments);
		mAdapterComment.notifyDataSetChanged();
		
		mListViewComment.setAdapter(mAdapterComment);
	}
	
	OnClickListener mSubmitPollButtonClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			mViewMode = READ_MODE;
			mLayoutFormControls.setVisibility(View.INVISIBLE);
			mLayoutCommentForm.setVisibility(View.VISIBLE);
			
			mAdapterAnswerChoice.setViewMode(READ_MODE);
			mAdapterAnswerChoice.notifyDataSetChanged();
		}
	};
	
	OnClickListener mViewCommentFormButtonClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			mLayoutFormControls.setVisibility(View.INVISIBLE);
			mLayoutCommentForm.setVisibility(View.VISIBLE);
		}
	};
	
	OnClickListener mSubmitCommentButtonClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			if (mViewMode == MODIFY_MODE) {
				mLayoutFormControls.setVisibility(View.VISIBLE);
				mLayoutCommentForm.setVisibility(View.INVISIBLE);
			}
		}
	};
	
	OnItemClickListener mAnswerChoiceItemClickListener = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
			AnswerChoice currentItem = (AnswerChoice) mAdapterAnswerChoice.getItem(position);
			String name = currentItem.getName();
			int count = currentItem.getVoterCount();
			
			Intent intent = new Intent(getBaseContext(), PollVoterListActivity.class);
			intent.putExtra("answer.choice", name + " (" + count + ")");
			startActivity(intent);
		}
	};
	
	@Override
	public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
		getSupportMenuInflater().inflate(R.menu.activity_poll_detail, menu);
		
		if (mPollType.equals("open")) {
			MenuItem itemShare = menu.findItem(R.id.menu_share);
			MenuItem itemInvite = menu.findItem(R.id.menu_invite);
			
			itemShare.setVisible(true);
			itemInvite.setVisible(false);
			//this.invalidateOptionsMenu();
		}
		else {
			MenuItem itemShare = menu.findItem(R.id.menu_share);
			MenuItem itemInvite = menu.findItem(R.id.menu_invite);
			
			itemShare.setVisible(false);
			itemInvite.setVisible(true);
			//this.invalidateOptionsMenu();
		}
		
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);

		switch (item.getItemId()) {
		case android.R.id.home:
			onBackPressed();
			// Intent intent = new Intent(this, MainActivity.class);
			// startActivity(intent);
			break;
		
		case R.id.menu_invite:
			Intent inviteIntent = new Intent(Intent.ACTION_SEND);

			inviteIntent.addCategory(Intent.CATEGORY_DEFAULT);
			inviteIntent.putExtra(Intent.EXTRA_SUBJECT, "subject here...");
			inviteIntent.putExtra(Intent.EXTRA_TEXT, "content here...");
			inviteIntent.putExtra(Intent.EXTRA_TITLE, "title here...");
			inviteIntent.setType("text/plain");    

			startActivity(Intent.createChooser(inviteIntent, getString(R.string.dialog_title_invite)));
			break;
		
		case R.id.menu_share:
			Intent shareIntent = new Intent(Intent.ACTION_SEND);

			shareIntent.addCategory(Intent.CATEGORY_DEFAULT);
			shareIntent.putExtra(Intent.EXTRA_SUBJECT, "subject here...");
			shareIntent.putExtra(Intent.EXTRA_TEXT, "content here...");
			shareIntent.putExtra(Intent.EXTRA_TITLE, "title here...");
			shareIntent.setType("text/plain");    

			startActivity(Intent.createChooser(shareIntent, getString(R.string.dialog_title_share)));
			break;
		}

		return true;
	}
	
	@Override
	public void onBackPressed() {
		if (mViewMode == MODIFY_MODE && mLayoutCommentForm.getVisibility() == View.VISIBLE) {
			mLayoutFormControls.setVisibility(View.VISIBLE);
			mLayoutCommentForm.setVisibility(View.INVISIBLE);
		}
		else {
			super.onBackPressed();
		}
	}
	
	/**
	 * Resizes the image proportionately so it fits the entire space.
	 */
	@SuppressWarnings("deprecation")
	private void setImageBitmap(Drawable d, ImageView imageView) {
		float width = getWindowManager().getDefaultDisplay().getWidth();

		BitmapDrawable drawable = (BitmapDrawable) d;
		Bitmap bitmap = drawable.getBitmap();

		float i = ((float) width) / ((float) bitmap.getWidth());
		float imageHeight = i * (bitmap.getHeight());
		TableRow.LayoutParams params = (TableRow.LayoutParams) imageView.getLayoutParams();
		params.height = (int) imageHeight;
		params.width = (int) width;
		imageView.setLayoutParams(params);
		imageView.setImageDrawable(d);
	}
	
	private List<AnswerChoice> loadAnswerChoices(String pollId) {
		List<AnswerChoice> choices = new ArrayList<AnswerChoice>();
		
		AnswerChoice choice = new AnswerChoice();
		choice.setSequence(1);
		choice.setName("Answer choice1");
		choice.setVoterCount(7);
		choice.setAnswerRate((double) choice.getVoterCount() / 31);
		choices.add(choice);
		
		choice = new AnswerChoice();
		choice.setSequence(2);
		choice.setName("Answer choice2 Answer choice2 Answer choice2 Answer choice2 Answer choice2 Answer choice2 Answer choice2 Answer choice2 Answer choice2");
		choice.setVoterCount(17);
		choice.setAnswerRate((double) choice.getVoterCount() / 31);
		choices.add(choice);
		
		choice = new AnswerChoice();
		choice.setSequence(3);
		choice.setName("Answer choice3");
		choice.setVoterCount(2);
		choice.setAnswerRate((double) choice.getVoterCount() / 31);
		choice.setImage(getResources().getDrawable(R.drawable.ic_6));
		choices.add(choice);
		
		choice = new AnswerChoice();
		choice.setSequence(4);
		choice.setName("Answer choice4");
		choice.setVoterCount(5);
		choice.setAnswerRate((double) choice.getVoterCount() / 31);
		choices.add(choice);
		
		return choices;
	}
	
	private List<Comment> loadComments(String pollId) {
		List<Comment> comments = new ArrayList<Comment>();
		
		Comment comment = new Comment();
		comment.setUsername("Sonya Cho");
		comment.setCreateDate("7.10");
		comment.setComment("This is good poll!");
		comments.add(comment);
		
		comment = new Comment();
		comment.setUsername("Louie Bae");
		comment.setCreateDate("7.9");
		comment.setComment("This is the best poll...");
		comments.add(comment);
		
		comment = new Comment();
		comment.setUsername("Kevin Bae");
		comment.setCreateDate("7.8");
		comment.setComment("I wanna go to Everland.");
		comments.add(comment);
		
		comment = new Comment();
		comment.setUsername("Minseo Bae");
		comment.setCreateDate("7.8");
		comment.setComment("I'm very very pretty.");
		comments.add(comment);
		
		return comments;
	}
	
}